//
//  TalkfunPreventCheatCountdown.swift
//  TalkfunSDKDemo
//
//  Created by 莫瑞权 on 2023/11/20.
//  Copyright © 2023 Talkfun. All rights reserved.
//

import UIKit

class TalkfunPreventCheatCountdown: UIView {
    
    

    let remind = TalkfunPreventCheatCountdownView(frame: CGRect(x: (UIScreen.main.bounds.width-280)/2, y: (UIScreen.main.bounds.height-280)/2, width: 280, height: 230))
    

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.frame = UIScreen.main.bounds
        //-----------
         addSubview(remind)
        

    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
    }
  

}


import AVFoundation

class TalkfunPreventCheatCountdownView: UIView {
    @objc public weak var delegate : TalkfunPreventCheatCountdownViewDelegate?
    
    var isShow:Bool = false
    
    let view = UIView()
    var audioPlayer: AVAudioPlayer?
    //签到的进度圈
    @objc public let round = TF_LivingProgress()
    @objc public let timeLabel = UILabel()
    let title = UILabel()
    let continueStudying = UIButton()
    let continueStudying_layer = CAGradientLayer()
    let shading = UIImageView(image: UIImage(named: "HTLive.bundle/fangzuobi"))
    
    let successView = UIView()
    let successViewImageView = UIImageView(image: UIImage(named: "HTLive.bundle/successfangzuobi"))
    let successViewTitle = UILabel()
    
 
    //倒计时总秒数
    var tempSeconds:NSInteger = 0
    //倒计时总秒数
    var totalSeconds:NSInteger = 0

    var countdownTime:Timer?
    
    func stopUI()
    {
        //固定倒计时
        if self.countdownTime != nil {
            self.countdownTime?.invalidate()
            self.countdownTime = nil
        }
    }
    func run(model: TFSignLoopPreventCheat)
    {
        self.view.isHidden = false
        self.successView.isHidden = true
        
        self.frame = CGRect(x: (UIScreen.main.bounds.width-280)/2, y: (UIScreen.main.bounds.height-280)/2, width: 280, height: 230)
        
        
        //固定倒计时
        if self.countdownTime != nil {
            self.countdownTime?.invalidate()
            self.countdownTime = nil
        }
        
//       self.tempSeconds = 60
        self.tempSeconds = model.validTime
        self.totalSeconds = self.tempSeconds
        self.timeLabel.text = self.stringFromInteger(totalSeconds);
        
        self.countdownTime = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(countdownTimeClick), userInfo: nil, repeats: true)
                RunLoop.main.add(self.countdownTime! , forMode: RunLoop.Mode.default)
     
        self.round.progressUI(value: 1)
    }
    
    @objc func countdownTimeClick()
    {
        
        if(self.tempSeconds>0)
        {
            self.tempSeconds = self.tempSeconds-1
            
            //比例
           let proportion = CGFloat(self.tempSeconds)/CGFloat(self.totalSeconds)
            
            self.round.progressUI(value: proportion)
            
            self.timeLabel.text = self.stringFromInteger(tempSeconds);
            
        }
        
        if(self.tempSeconds==0)
        {
   
            if self.countdownTime != nil {
                self.countdownTime?.invalidate()
                self.countdownTime = nil
            }
         
            self.delegate?.countdownEnds()

            
        }
       
        
        
    }
    func stringFromInteger(_ seconds: NSInteger) -> String {
        let minutesPart = seconds / 60  // 计算分钟数
        let secondsPart = seconds % 60  // 计算剩余秒数

        // 使用 String(format:) 来格式化字符串
        return String(format: "%02d:%02d", minutesPart, secondsPart)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(view)
        view.backgroundColor = UIColor(red: 255, green: 255, blue: 255, alpha: 1)
        view.layer.masksToBounds = true
        view.layer.cornerRadius = 12

       
        //----倒计时-----
        view.addSubview(self.round)
        self.round.backgroundColor = .clear
        self.round.layer.masksToBounds  =  true
        round.speedColor = UIColor(red: 255/255.0, green: 136/255.0, blue: 0, alpha: 1)
        round.wholeColor = UIColor(red: 255/255.0, green: 224/255.0, blue: 200/255.0, alpha: 1)
         self.round.addSubview(self.timeLabel)
         self.timeLabel.numberOfLines = 0;
         self.round.addSubview(self.timeLabel)
         self.timeLabel.font = UIFont.nameFang("PingFang SC-Bold", size: 24)
         self.timeLabel.text = "00:00";
         self.timeLabel.textAlignment =  .center
         self.timeLabel.textColor = UIColor(red: 255/255.0, green: 136/255.0, blue: 0, alpha: 1.0)


        //-------
    
        view.addSubview(continueStudying)
        continueStudying.addTarget(self, action: #selector(continueStudyingClick), for: .touchUpInside)
        // 设置按钮的标题字体
        continueStudying.titleLabel?.font = UIFont.nameFang("PingFang SC-Regular", size: 20)

        // 设置按钮的标题
        continueStudying.setTitle("继续学习", for: .normal)

        // 设置按钮标题的颜色
        continueStudying.setTitleColor(UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1), for: .normal)

        // 设置按钮的阴影
        continueStudying.layer.shadowColor = UIColor(red: 255/255.0, green: 114/255.0, blue: 78/255.0, alpha: 0.4).cgColor
        continueStudying.layer.shadowOffset = CGSize(width: 0, height: 4)
        continueStudying.layer.shadowOpacity = 1
        continueStudying.layer.shadowRadius = 12

        continueStudying_layer.colors = [UIColor(red: 255/255.0, green: 172/255.0, blue: 77/255.0, alpha: 1).cgColor,
                                         UIColor(red: 255/255.0, green: 114/255.0, blue: 78/255.0, alpha: 1).cgColor]
        continueStudying_layer.locations = [0, 1]
        continueStudying_layer.startPoint = CGPoint(x: 0.5, y: 0)
        continueStudying_layer.endPoint = CGPoint(x: 1, y: 1)

        // 将渐变层添加到按钮上
        continueStudying.layer.insertSublayer(continueStudying_layer, at: 0)

        view.addSubview(shading)
        view.addSubview(title)
        title.textColor = UIColor(red: 255/255.0, green: 167/255.0, blue: 77/255.0, alpha: 1)
        title.font = UIFont.nameFang("PingFang SC-Regular", size: 12)
        title.text = "每天进步一点点，再接再厉，加油~"
        title.textAlignment = .center
        
        self.round.progressUI(value: 1)
        
        
        
        
        //-----------学时防作弊签到成功-------------
          self.addSubview(successView)
          successView.backgroundColor = UIColor(red: 255, green: 255, blue: 255, alpha: 1)
          successView.isHidden = true
          successView.layer.masksToBounds = true
          successView.layer.cornerRadius = 12
      
          successView.addSubview(successViewImageView)
          successViewTitle.numberOfLines = 0
          successViewTitle.text = "签到成功"
          successViewTitle.font = UIFont.nameFang("PingFang SC-Regular", size: 18)
          successViewTitle.textColor = UIColor(red: 27/255, green: 57/255, blue: 71/255, alpha: 1)
          successViewTitle.textAlignment = .center
          successView.addSubview(successViewTitle)
        

    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        view.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
        self.round.frame = CGRect(x: (view.frame.size.width - 100) / 2, y:27, width: 100, height: 100)
        self.timeLabel.frame = CGRect(x: 0, y: (self.round.frame.size.height - 33)/2, width: self.round.frame.size.width, height: 33)
        
        shading.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 80)
        title.frame = CGRect(x: 0, y: 135, width: view.frame.width, height: 17)
        
        continueStudying.frame = CGRect(x: (view.frame.width-180)/2, y: 160, width: 180, height: 44)
        continueStudying.layer.masksToBounds = true
        continueStudying.layer.cornerRadius = continueStudying.frame.height/2
        // 创建并设置渐变层
        continueStudying_layer.frame = continueStudying.bounds
        //-------
        successView.frame = CGRect(x: (self.frame.width-173)/2, y: (self.frame.height-172)/2, width: 173, height: 172)
     
        successViewImageView.frame = CGRect(x: (successView.frame.width-130)/2, y: 28, width: 130, height: 78)
        successViewTitle.frame = CGRect(x: 0, y: 124, width: successView.frame.width, height: 25)
    }
    //继续学习点击
    @objc func continueStudyingClick()
    {
        if self.countdownTime != nil {
            self.countdownTime?.invalidate()
            self.countdownTime = nil
        }
        self.frame = CGRect(x: (UIScreen.main.bounds.width-173)/2, y: (UIScreen.main.bounds.height-172)/2, width: 173, height: 172)
        self.layoutSubviews()
        self.view.isHidden = true
        
        self.delegate?.continueStudying(completion: {[weak self] code, msg in
            guard let `self` = self else { return }
            
            if(code==0)
            {
                self.successView.isHidden = false
                
                self.playSound(name:"SuccessfulCheckSound")
                DispatchQueue.main.asyncAfter(deadline: .now() + 1.1) { [weak self] in
                    guard let `self` = self else { return }
                    
                    self.successView.isHidden = true
                    
                    if let superview = self.superview
                    {
                        superview.removeFromSuperview()
                    }
                }
                
            }else
            {
                if let superview = self.superview
                {
                    superview.removeFromSuperview()
                }
                
                self.toast(msg, position: CGPoint(x: UIScreen.main.bounds.width/2, y: UIScreen.main.bounds.height/2))
                
                
                
            }
            self.isShow = false

        
        })
  
    }
    func playSound(name: String) {
        // 获取TFMedia.bundle的路径
        guard let bundlePath = Bundle.main.path(forResource: "TFMedia", ofType: "bundle"),
              let bundle = Bundle(path: bundlePath) else {
            print("无法找到TFMedia.bundle")
            return
        }

        // 在TFMedia.bundle中查找音频文件
        if let path = bundle.path(forResource: name, ofType: "mp3") {
            let url = URL(fileURLWithPath: path)

            do {
                audioPlayer = try AVAudioPlayer(contentsOf: url)
            } catch {
                print("无法创建播放器或找不到文件")
                return
            }
        } else {
            print("在TFMedia.bundle中找不到文件")
            return
        }

        audioPlayer?.play()
    }


}
@objc protocol TalkfunPreventCheatCountdownViewDelegate : NSObjectProtocol {
    
    /**倒计时结束**/
    func countdownEnds()
    /**继续学习**/
    func continueStudying(completion: @escaping (Int, String) -> Void)
    
}
